﻿Imports System.IO
Imports iComm.DB
Public Class ClsDirectory

    Private _dirPath As String

    Dim tblFileTemplate As New DataTable
    Dim tblFolderTemplate As New DataTable
    Dim dbFile As New DataTable
    Dim dbFolder As New DataTable
    Dim tempCsvPath As String = "c:\work\"


    Sub New()

    End Sub
    Sub New(ByVal _dirPath As String)
        '"\"を抜いて、保存する
        Me.DirPath = _dirPath
    End Sub

    Public Property DirPath() As String
        Get
            If String.IsNullOrEmpty(_dirPath) Then Return _dirPath
            Return IIf(Right(_dirPath.Trim, 1).Equals("\"), Left(_dirPath.Trim, _dirPath.Trim.Length - 1), _dirPath)
        End Get
        Set(ByVal Value As String)
            _dirPath = Value
        End Set
    End Property

    Public Structure ColFormat
        Public name As String
        Public type As String
        Public Sub New(ByVal name As String, ByVal type As String)
            Me.name = name
            Me.type = type
        End Sub
    End Structure

    Public Structure FileFormat
        Public Shared id As ColFormat = New ColFormat("id", "System.String")
        Public Shared name As ColFormat = New ColFormat("name", "System.String")
        Public Shared type As ColFormat = New ColFormat("type", "System.String")
        Public Shared size As ColFormat = New ColFormat("size", "System.Decimal")
        Public Shared dateCreated As ColFormat = New ColFormat("dateCreated", "System.DateTime")
        Public Shared dateLastModified As ColFormat = New ColFormat("dateLastModified", "System.DateTime")
        Public Shared dateLastAccessed As ColFormat = New ColFormat("dateLastAccessed", "System.DateTime")
    End Structure


    ''' <summary>
    ''' ローカルフォルダ構造をDBサーバに登録
    ''' </summary>
    ''' <returns>処理結果</returns>
    ''' <exception cref="Exception">処理失敗</exception>
    Public Function importCsvToDB(ByVal strTable As String, Optional ByVal strPath As String = Nothing, Optional ByVal dt As DataTable = Nothing) As Integer

        Dim clsSQL As New MysqlHelper()
        Dim retCnt As Integer = Nothing
        Try
            If dt IsNot Nothing Then
                Dim csv As New ClsCSV
                ' My.Application.Info.DirectoryPath & "\"
                strPath = tempCsvPath + DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv"
                csv.ConvertDataTableToCsv(dt, strPath, False)

            End If

            '
            Dim clsUtilities As New DB.MysqlUtilities()
            clsUtilities.SQL_import_csv_value(0).ParamValue = ReplaceSpecialSign(strPath, "\", 2)
            clsUtilities.SQL_import_csv = String.Format(clsUtilities.SQL_import_csv, strTable)
            Dim param As MySql.Data.MySqlClient.MySqlParameter() = clsUtilities.GetParam(clsUtilities.SQL_import_csv_value)

            retCnt = clsSQL.RunSQL(clsUtilities.SQL_import_csv, param)

            If dt IsNot Nothing Then
                System.IO.File.Delete(strPath)
            End If

            Return retCnt
        Catch ex As Exception
            SystemError.SystemLog(ex)
            Return -1
        Finally
            clsSQL.Dispose()
            clsSQL = Nothing
        End Try
    End Function

    Public Sub testMain()
        'Me.FolderPath = "C:\Users\shin\work\00 work\iHelper\test\logs"
        checkFolderPath()

    End Sub

    ''' <summary>
    ''' CSVファイルをDBサーバに導入
    ''' </summary>
    ''' <returns>処理結果</returns>
    ''' <exception cref="Exception">処理失敗</exception>
    Public Function getFolderOrFileId(ByVal strPath As String, ByVal strKubun As String) As Integer

        Dim clsSQL As New MysqlHelper()
        Dim retCnt As Integer = 0
        Try

            '
            Dim clsUtilities As New DB.MysqlUtilities()
            clsUtilities.PRC_Folder_File_Path_Value(0).ParamValue = strPath
            clsUtilities.PRC_Folder_File_Path_Value(1).ParamValue = strKubun
            Dim param As MySql.Data.MySqlClient.MySqlParameter() = clsUtilities.GetParam(clsUtilities.PRC_Folder_File_Path_Value)
            retCnt = clsSQL.RunProc_ForReturnString(clsUtilities.PRC_Folder_File_GetId, param)

            Return retCnt
        Catch ex As Exception
            SystemError.SystemLog(ex)
            Return -1
        Finally
            clsSQL.Dispose()
            clsSQL = Nothing
        End Try
    End Function

    ''' <summary>
    ''' ローカルフォルダ構造をDBサーバに登録
    ''' </summary>
    ''' <returns>処理結果</returns>
    ''' <exception cref="Exception">処理失敗</exception>
    Public Function insertFolderToDB(ByVal tbl As DataTable) As Boolean

        Dim clsSQL As New MysqlHelper()
        Try

            'フォルダテーブルにデータを挿入
            If tbl.Rows.Count > 0 Then clsSQL.SqlBulkInsert(tbl, "dat_folder")

            Return True
        Catch ex As Exception
            SystemError.SystemLog(ex)
            Return False
        Finally
            clsSQL.Dispose()
            clsSQL = Nothing
        End Try
    End Function

    ''' <summary>
    ''' ローカルフォルダ構造をDBサーバに登録
    ''' </summary>
    ''' <returns>処理結果</returns>
    ''' <exception cref="Exception">処理失敗</exception>
    Public Function insertFileToDB(ByVal tbl As DataTable) As Boolean

        Dim clsSQL As New MysqlHelper()
        Try

            'ファイルテーブルにデータを挿入
            If tbl.Rows.Count > 0 Then clsSQL.SqlBulkInsert(tbl, "dat_file")

            Return True
        Catch ex As Exception
            SystemError.SystemLog(ex)
            Return False
        Finally
            clsSQL.Dispose()
            clsSQL = Nothing
        End Try
    End Function

    ''' <summary>
    ''' ローカルフォルダ構造をDBサーバに登録
    ''' </summary>
    ''' <returns>処理結果</returns>
    ''' <exception cref="Exception">処理失敗</exception>
    Public Function updateFileToDB(ByVal tbl As DataTable) As Boolean

        Dim clsSQL As New MysqlHelper()
        Try

            'ファイルテーブルにデータを挿入
            If tbl.Rows.Count > 0 Then clsSQL.SqlBulkUpdate(tbl, "dat_file")

            Return True
        Catch ex As Exception
            SystemError.SystemLog(ex)
            Return False
        Finally
            clsSQL.Dispose()
            clsSQL = Nothing
        End Try
    End Function

    ''' <summary>
    ''' ローカルフォルダ構造をDBサーバに登録
    ''' </summary>
    ''' <returns>処理結果</returns>
    ''' <exception cref="Exception">処理失敗</exception>
    Public Function updateRootToDB(ByVal tbl As DataTable) As Boolean

        Dim clsSQL As New MysqlHelper()
        Dim clsUtilities As New MysqlUtilities
        Try

            'ファイルテーブルにデータを挿入
            If tbl.Rows.Count > 0 Then clsSQL.SqlBulkUpdate2(tbl, clsUtilities.SQL_FileRoot_select)

            Return True
        Catch ex As Exception
            SystemError.SystemLog(ex)
            Return False
        Finally
            clsSQL.Dispose()
            clsSQL = Nothing
        End Try
    End Function

    Public Function insertRootToDB() As Integer
        Dim cnt As Integer = 0
        Dim strSql As String
        Dim clsSQL As New MysqlHelper()

        strSql = "select IFNULL(max(id)+1,1) as maxid from mldn.dat_fileroot "
        Dim tblMaxId As New DataTable
        clsSQL.RunProc(strSql, tblMaxId)
        Dim intMaxId As Integer = tblMaxId.Rows(0)(0)

        'ローカルファイルテーブルの初期化
        initFileOrFolderTable(tblFolderTemplate)
        'ローカルファイルテーブルの初期化
        initFileOrFolderTable(tblFileTemplate, True)
        'ローカルデータの読み込み
        readFolderToTable(tblFileTemplate, tblFolderTemplate, intMaxId, DirPath, True)

        Dim clsUtilities As New DB.MysqlUtilities()
        Dim dtNow As DateTime = GetDateTimeUTtcOrLocal(0)
        clsUtilities.SQL_FileRoot_Insert_Value(0).ParamValue = intMaxId
        clsUtilities.SQL_FileRoot_Insert_Value(1).ParamValue = intMaxId
        clsUtilities.SQL_FileRoot_Insert_Value(2).ParamValue = System.Net.Dns.GetHostName
        clsUtilities.SQL_FileRoot_Insert_Value(3).ParamValue = DirPath
        clsUtilities.SQL_FileRoot_Insert_Value(4).ParamValue = dtNow
        clsUtilities.SQL_FileRoot_Insert_Value(5).ParamValue = dtNow
        clsUtilities.SQL_FileRoot_Insert_Value(6).ParamValue = dtNow
        Dim param As MySql.Data.MySqlClient.MySqlParameter() = clsUtilities.GetParam(clsUtilities.SQL_FileRoot_Insert_Value)
        cnt = clsSQL.RunSQL(clsUtilities.SQL_FileRoot_Insert, param)

        Return intMaxId
    End Function

    ''' <summary>
    ''' ローカルフォルダ構造をDBサーバに登録
    ''' </summary>
    ''' <returns>処理結果</returns>
    ''' <exception cref="Exception">処理失敗</exception>
    Public Function insertFileAndFolderFromLocalToDB(Optional ByVal intDirId As Integer = 0) As Boolean

        Dim cnt As Integer = 0
        Dim intMaxId As Integer = 0
        Dim clsSQL As New MysqlHelper()
        Try
            If intDirId = 0 Then
                intMaxId = insertRootToDB()
            Else
                intMaxId = intDirId
            End If

            'ローカルファイルテーブルの初期化
            initFileOrFolderTable(tblFolderTemplate)
            'ローカルファイルテーブルの初期化
            initFileOrFolderTable(tblFileTemplate, True)
            'ローカルデータの読み込み
            readFolderToTable(tblFileTemplate, tblFolderTemplate, intMaxId, DirPath, True)

     
            Dim cntCSV As Integer = 0

            'ファイルテーブルにデータを挿入
            'If tblFileTemplate.Rows.Count > 0 Then clsSQL.SqlBulkInsert(tblFileTemplate, "dat_file")
            If tblFileTemplate.Rows.Count > 0 Then
                cntCSV = importCsvToDB("dat_file", "", tblFileTemplate)
            End If
            'フォルダテーブルにデータを挿入
            'If tblFolderTemplate.Rows.Count > 0 Then clsSQL.SqlBulkInsert(tblFolderTemplate, "dat_folder")
            If cntCSV >= 0 AndAlso tblFolderTemplate.Rows.Count > 0 Then
                cntCSV = importCsvToDB("dat_folder", "", tblFolderTemplate)
            End If

            If cntCSV < 0 Then
                Return False
            End If

            Return True
        Catch ex As Exception
            SystemError.SystemLog(ex)
            Return False
        End Try
    End Function

    ''' <summary>
    ''' ローカルフォルダ構造をDBサーバに更新
    ''' </summary>
    ''' <returns>処理結果</returns>
    ''' <exception cref="Exception">処理失敗</exception>
    Public Function updateFileAndFolderFromLocalToDB(ByVal intId As Integer, ByVal dtRoot As DataTable) As Boolean
        Dim strSql As String = Nothing
        'データベースからデータを取得
        Dim clsSQL As New MysqlHelper()
        Dim strTargetId As String = Nothing
        Dim lstOldTargetId As New List(Of String)

        Try

            For i = 0 To dtRoot.Rows.Count - 1
                lstOldTargetId.Add(dtRoot.Rows(i)("targetId"))
            Next

            '監視対象ファイルリストをローカル変数に読み込み

            'ローカルファイルテーブルの初期化
            initFileOrFolderTable(tblFolderTemplate)
            'ローカルファイルテーブルの初期化
            initFileOrFolderTable(tblFileTemplate, True)
            'ローカルデータの読み込み
            readFolderToTable(Me.tblFileTemplate, Me.tblFolderTemplate, intId, DirPath, True, _
                             dtRoot, strTargetId)

            Dim clsUtilities As New DB.MysqlUtilities()
            For i = 0 To dtRoot.Rows.Count - 1
                If lstOldTargetId(i).Equals(dtRoot.Rows(i)("targetId")) Then
                    Continue For
                End If

                If dtRoot.Rows(i)("id").Equals(intId) Then
                    '更新
                    clsUtilities.SQL_FileRoot_Update_Value(0).ParamValue = dtRoot.Rows(i)("targetId")
                    clsUtilities.SQL_FileRoot_Update_Value(1).ParamValue = DirPath
                    clsUtilities.SQL_FileRoot_Update_Value(2).ParamValue = dtRoot.Rows(i)("id")
                    Dim param As MySql.Data.MySqlClient.MySqlParameter() = clsUtilities.GetParam(clsUtilities.SQL_FileRoot_Update_Value)
                    Dim cnt = clsSQL.RunSQL(clsUtilities.SQL_FileRoot_Update, param)
                    '削除
                    clsUtilities.SQL_FileRoot_delete_Value(0).ParamValue = dtRoot.Rows(i)("id")
                    param = clsUtilities.GetParam(clsUtilities.SQL_FileRoot_delete_Value)
                    cnt = clsSQL.RunSQL(clsUtilities.SQL_FileRoot_delete, param)
                    '挿入
                    Dim dtNow As DateTime = GetDateTimeUTtcOrLocal(0)
                    clsUtilities.SQL_FileRoot_Insert_Value(0).ParamValue = dtRoot.Rows(i)("id")
                    clsUtilities.SQL_FileRoot_Insert_Value(1).ParamValue = dtRoot.Rows(i)("id")
                    clsUtilities.SQL_FileRoot_Insert_Value(2).ParamValue = dtRoot.Rows(i)("computerName")
                    clsUtilities.SQL_FileRoot_Insert_Value(3).ParamValue = DirPath
                    clsUtilities.SQL_FileRoot_Insert_Value(4).ParamValue = dtNow
                    clsUtilities.SQL_FileRoot_Insert_Value(5).ParamValue = dtNow
                    clsUtilities.SQL_FileRoot_Insert_Value(6).ParamValue = dtNow
                    param = clsUtilities.GetParam(clsUtilities.SQL_FileRoot_Insert_Value)
                    cnt = clsSQL.RunSQL(clsUtilities.SQL_FileRoot_Insert, param)
                Else
                    '更新
                    clsUtilities.SQL_FileRoot_Update_Value(0).ParamValue = dtRoot.Rows(i)("targetId")
                    clsUtilities.SQL_FileRoot_Update_Value(1).ParamValue = dtRoot.Rows(i)("path")
                    clsUtilities.SQL_FileRoot_Update_Value(2).ParamValue = dtRoot.Rows(i)("id")
                    Dim param As MySql.Data.MySqlClient.MySqlParameter() = clsUtilities.GetParam(clsUtilities.SQL_FileRoot_Update_Value)
                    Dim cnt = clsSQL.RunSQL(clsUtilities.SQL_FileRoot_Update, param)

                    '削除
                    clsUtilities.SQL_FileRoot_delete_Value(0).ParamValue = dtRoot.Rows(i)("id")
                    param = clsUtilities.GetParam(clsUtilities.SQL_FileRoot_delete_Value)
                    cnt = clsSQL.RunSQL(clsUtilities.SQL_FileRoot_delete, param)
                End If
            Next


            Dim cntCSV As Integer = 0

            'ファイルテーブルにデータを挿入
            'If tblFileTemplate.Rows.Count > 0 Then clsSQL.SqlBulkInsert(tblFileTemplate, "dat_file")
            If tblFileTemplate.Rows.Count > 0 Then
                cntCSV = importCsvToDB("dat_file", "", tblFileTemplate)
            End If
            'フォルダテーブルにデータを挿入
            'If tblFolderTemplate.Rows.Count > 0 Then clsSQL.SqlBulkInsert(tblFolderTemplate, "dat_folder")
            If cntCSV >= 0 AndAlso tblFolderTemplate.Rows.Count > 0 Then
                cntCSV = importCsvToDB("dat_folder", "", tblFolderTemplate)
            End If

            If cntCSV < 0 Then
                Return False
            End If

            Return True
        Catch ex As Exception
            SystemError.SystemLog(ex)
            Return False
        End Try
    End Function

    ''' <summary>
    ''' ローカルフォルダ構造をDBサーバに更新
    ''' </summary>
    ''' <returns>処理結果</returns>
    ''' <exception cref="Exception">処理失敗</exception>
    Public Function updateFileOrFolderToDB(ByVal tbl As DataTable) As Boolean
        Dim clsSQL As New MysqlHelper()
        Try

            Dim clsUtilities As New DB.MysqlUtilities()
            Dim strSql As String
            Dim SQL_update_Value As iComm.DB.MysqlUtilities.STC_Item()

            If tbl.TableName.Equals(ClsStatic.CST_FILE) Then
                strSql = clsUtilities.SQL_File_update
                SQL_update_Value = clsUtilities.SQL_File_update_Value

                SQL_update_Value(2).ParamValue = tbl.Rows(0)(2)
                SQL_update_Value(3).ParamValue = tbl.Rows(0)(3)
            Else
                strSql = clsUtilities.SQL_Folder_update
                SQL_update_Value = clsUtilities.SQL_Folder_update_Value
            End If
            SQL_update_Value(0).ParamValue = tbl.Rows(0)(0)
            SQL_update_Value(1).ParamValue = tbl.Rows(0)(1)
            SQL_update_Value(4).ParamValue = tbl.Rows(0)(4)
            SQL_update_Value(5).ParamValue = tbl.Rows(0)(5)
            SQL_update_Value(6).ParamValue = tbl.Rows(0)(6)
            Dim param As MySql.Data.MySqlClient.MySqlParameter() = clsUtilities.GetParam(SQL_update_Value)
            Return clsSQL.RunSQL(strSql, param)

        Catch ex As Exception
            SystemError.SystemLog(ex)
            Return False
        Finally
            clsSQL.Dispose()
            clsSQL = Nothing
        End Try
    End Function

    ''' <summary>
    ''' ローカルフォルダ構造をDBサーバに更新
    ''' </summary>
    ''' <returns>処理結果</returns>
    ''' <exception cref="Exception">処理失敗</exception>
    Public Function deleteFileOrFolderToDB(ByVal strPath As String) As Boolean
        Dim clsSQL As New MysqlHelper()
        Try

            Dim clsUtilities As New DB.MysqlUtilities()
            Dim param As MySql.Data.MySqlClient.MySqlParameter()

            clsUtilities.PRC_Folder_File_Delete_Value(0).ParamValue = strPath
            param = clsUtilities.GetParam(clsUtilities.PRC_Folder_File_Delete_Value)
            Return clsSQL.RunProc3(clsUtilities.PRC_Folder_File_Delete, param)

        Catch ex As Exception
            SystemError.SystemLog(ex)
            Return False
        Finally
            clsSQL.Dispose()
            clsSQL = Nothing
        End Try
    End Function

    ''' <summary>
    ''' 監視対象がDBサーバには存在するかチェック
    ''' </summary>
    ''' <returns>処理結果
    ''' 0：不存在
    ''' 1：含めてる監視対象が存在する
    ''' 2：含められてる監視対象が存在する
    ''' 3：存在
    ''' </returns>
    ''' <exception cref="Exception">処理失敗</exception>
    Public Function checkFolderPath() As Integer
        Dim dtRoot As New DataTable
        Dim strId As String
        Try
            If Not System.IO.Directory.Exists(Me.DirPath) Then
                Return -1
            End If

            selectRootFromDB(dtRoot)
            If dtRoot.Rows.Count > 0 Then
                strId = dtRoot.Rows(0)("id")

                '存在する場合、登録不要
                For i = 0 To dtRoot.Rows.Count - 1
                    If Me.DirPath.Equals(dtRoot.Rows(i)("path")) Then
                        Return 3
                    End If
                Next
                '含められてる監視対象が存在する場合
                For i = 0 To dtRoot.Rows.Count - 1
                    If DirPath.IndexOf(dtRoot.Rows(i)("path")) >= 0 Then
                        Return 2
                    End If
                Next
                '含めてる監視対象が存在する場合、更新
                'If strPath.IndexOf(DirPath) >= 0 Then
                '    updateFileAndFolderFromLocalToDB(strId, strPath)
                '    Return 1
                'End If
                For i = 0 To dtRoot.Rows.Count - 1
                    If dtRoot.Rows(i)("path").IndexOf(DirPath) >= 0 Then
                        updateFileAndFolderFromLocalToDB(dtRoot.Rows(i)("id"), dtRoot)
                        Return 1
                    End If
                Next
            End If

            insertFileAndFolderFromLocalToDB()

            Return 0
        Catch ex As Exception
            SystemError.SystemLog(ex)
            Return -1
        End Try
    End Function

    ''' <summary>
    ''' 監視対象がDBサーバに保存してるパルを取得
    ''' </summary>
    ''' <returns>処理結果</returns>
    ''' <exception cref="Exception">処理失敗</exception>
    Public Function selectRootFromDB(ByRef tblRoot As DataTable) As Boolean
        Try
            'データベースからデータを取得
            Dim clsSQL As New MysqlHelper()
            Dim clsUtilities As New MysqlUtilities
            Dim strWhere As String = ""
            If Not String.IsNullOrEmpty(Me.DirPath) Then
                strWhere = "where concat(path,'\\') like '" & ReplaceSpecialSign(DirPath & "\", "\", 4) & "%'"
            End If

            Dim strSql As String = clsUtilities.SQL_FileRoot_select & strWhere
            tblRoot = clsSQL.GetSQLdataTbl(strSql)

            Return True
        Catch ex As Exception
            SystemError.SystemLog(ex)
            Return Nothing
        End Try
    End Function

    ''' <summary>
    ''' 監視対象がDBサーバに保存してるパルを取得
    ''' </summary>
    ''' <returns>処理結果</returns>
    ''' <exception cref="Exception">処理失敗</exception>
    Public Function selectRootFromDB(ByRef tblRoot As DataSet) As Boolean
        Try
            'データベースからデータを取得
            Dim clsSQL As New MysqlHelper()
            Dim clsUtilities As New MysqlUtilities
            Dim strWhere As String = ""
            If Not String.IsNullOrEmpty(Me.DirPath) Then
                strWhere = "where concat(path,'\\') like '" & ReplaceSpecialSign(DirPath & "\", "\") & "%'"
            End If

            Dim strSql As String = clsUtilities.SQL_FileRoot_select & strWhere
            tblRoot = clsSQL.GetSQLdataSet(strSql)

            Return True
        Catch ex As Exception
            SystemError.SystemLog(ex)
            Return Nothing
        End Try
    End Function

    ''' <summary>
    ''' '读取一个文件夹下的所有文件名，abc为是否读取子文件夹
    ''' </summary>
    ''' <returns>処理結果</returns>
    ''' <exception cref="Exception">処理失敗</exception>
    Private Function readFolderToTable(ByVal strId As String, ByVal strPath As String, _
                                       ByVal isReadChildFolder As Boolean) As Boolean
        Dim dirInfo As New DirectoryInfo(strPath)
        Dim subdirInfo As DirectoryInfo
        '读取目录的文件
        Dim fInfo As FileInfo
        Dim drRow As DataRow
        Dim i As Long = 0

        Try

            For Each fInfo In dirInfo.GetFiles
                i = i + 1

                drRow = Me.tblFileTemplate.NewRow
                drRow.Item(FileFormat.id.name) = strId & "-" & i
                drRow.Item(FileFormat.name.name) = fInfo.Name
                drRow.Item(FileFormat.type.name) = fInfo.Extension
                drRow.Item(FileFormat.size.name) = fInfo.Length
                drRow.Item(FileFormat.dateCreated.name) = fInfo.CreationTimeUtc
                drRow.Item(FileFormat.dateLastAccessed.name) = fInfo.LastAccessTimeUtc
                drRow.Item(FileFormat.dateLastModified.name) = fInfo.LastWriteTimeUtc
                Me.tblFileTemplate.Rows.Add(drRow)
            Next
            fInfo = Nothing

            i = 0
            If isReadChildFolder = True Then
                '用递归读取所有子目录
                For Each subdirInfo In dirInfo.GetDirectories
                    i = i + 1

                    drRow = Me.tblFolderTemplate.NewRow
                    drRow.Item(FileFormat.id.name) = strId & "_" & i
                    drRow.Item(FileFormat.name.name) = subdirInfo.Name
                    'drRow.Item(FileFormat.type.name) = fInfo.Extension
                    'drRow.Item(FileFormat.size.name) = fInfo.Length
                    drRow.Item(FileFormat.dateCreated.name) = subdirInfo.CreationTimeUtc
                    drRow.Item(FileFormat.dateLastAccessed.name) = subdirInfo.LastAccessTimeUtc
                    drRow.Item(FileFormat.dateLastModified.name) = subdirInfo.LastWriteTimeUtc

                    Me.tblFolderTemplate.Rows.Add(drRow)

                    readFolderToTable(strId & "_" & i, subdirInfo.FullName, isReadChildFolder)
                Next
            End If
            Return True
        Catch ex As Exception
            SystemError.SystemLog(ex)
            Return False
        Finally
            dirInfo = Nothing
            subdirInfo = Nothing
            fInfo = Nothing
            drRow = Nothing
        End Try
    End Function

    ''' <summary>
    ''' '读取一个文件夹下的所有文件名，isReadChildFolder为是否读取子文件夹
    ''' </summary>
    ''' <returns>処理結果</returns>
    ''' <exception cref="Exception">処理失敗</exception>
    Private Function readFolderToTable(ByRef fileTable As DataTable, ByRef folderTable As DataTable, _
                                       ByVal strId As String, ByVal strPath As String, _
                                       ByVal isReadChildFolder As Boolean, _
                                       Optional ByRef dtRoot As DataTable = Nothing, _
                                       Optional ByRef ref_TargetId As String = Nothing) As Boolean
        Dim dirInfo As New DirectoryInfo(strPath)
        Dim subdirInfo As DirectoryInfo
        '读取目录的文件
        Dim fInfo As FileInfo
        Dim drRow As DataRow
        Dim i As Long = 0

        Try

            For Each fInfo In dirInfo.GetFiles
                i = i + 1

                drRow = fileTable.NewRow
                drRow.Item(FileFormat.id.name) = strId & "-" & i
                drRow.Item(FileFormat.name.name) = fInfo.Name
                drRow.Item(FileFormat.type.name) = fInfo.Extension
                drRow.Item(FileFormat.size.name) = fInfo.Length
                drRow.Item(FileFormat.dateCreated.name) = fInfo.CreationTimeUtc
                drRow.Item(FileFormat.dateLastAccessed.name) = fInfo.LastAccessTimeUtc
                drRow.Item(FileFormat.dateLastModified.name) = fInfo.LastWriteTimeUtc
                fileTable.Rows.Add(drRow)
            Next
            fInfo = Nothing

            i = 0
            If isReadChildFolder = True Then
                '用递归读取所有子目录
                For Each subdirInfo In dirInfo.GetDirectories
                    i = i + 1

                    drRow = folderTable.NewRow
                    drRow.Item(FileFormat.id.name) = strId & "_" & i
                    drRow.Item(FileFormat.name.name) = subdirInfo.Name
                    'drRow.Item(FileFormat.type.name) = fInfo.Extension
                    'drRow.Item(FileFormat.size.name) = fInfo.Length
                    drRow.Item(FileFormat.dateCreated.name) = subdirInfo.CreationTimeUtc
                    drRow.Item(FileFormat.dateLastAccessed.name) = subdirInfo.LastAccessTimeUtc
                    drRow.Item(FileFormat.dateLastModified.name) = subdirInfo.LastWriteTimeUtc

                    folderTable.Rows.Add(drRow)


                    'If existFolder IsNot Nothing AndAlso existFolder.Equals(subdirInfo.FullName) Then
                    '    ref_TargetId = strId & "_" & j
                    '    Continue For
                    'End If
                    Dim tempflg As Boolean = False
                    If dtRoot IsNot Nothing Then
                        For j = 0 To dtRoot.Rows.Count - 1
                            If subdirInfo.FullName.Equals(dtRoot.Rows(j)("path")) Then
                                dtRoot.Rows(j)("targetId") = strId & "_" & i
                                tempflg = True
                                Exit For
                            End If
                        Next
                    End If
                    If tempflg Then Continue For

                    readFolderToTable(fileTable, folderTable, strId & "_" & i, subdirInfo.FullName, isReadChildFolder)
                Next
            End If
            Return True
        Catch ex As Exception
            SystemError.SystemLog(ex)
            Return False
        Finally
            dirInfo = Nothing
            subdirInfo = Nothing
            fInfo = Nothing
            drRow = Nothing
        End Try
    End Function

    Public Function initFileOrFolderTable(ByRef dt As DataTable, Optional ByVal isFileFormat As Boolean = False) As Boolean
        Try
            dt = New DataTable
            'テーブルにフィールドを追加
            'Dim colId As DataColumn
            '' Create column 1.
            'colId = New DataColumn()
            'colId.DataType = System.Type.GetType("System.String")
            'colId.ColumnName = "id"
            '' Add the column to the DataTable.Columns collection.
            'dt.Columns.Add(colId)

            dt.Columns.Add("id", Type.GetType("System.String"))
            dt.Columns.Add("name", Type.GetType("System.String"))

            If isFileFormat Then
                dt.Columns.Add("type", Type.GetType("System.String"))
                dt.Columns.Add("size", Type.GetType("System.Decimal"))
                dt.TableName = ClsStatic.CST_FILE
            Else
                dt.TableName = ClsStatic.CST_FOLDER
            End If

            dt.Columns.Add("dateCreated", Type.GetType("System.DateTime"))
            dt.Columns.Add("dateLastModified", Type.GetType("System.DateTime"))
            dt.Columns.Add("dateLastAccessed", Type.GetType("System.DateTime"))


            Dim keys(0) As DataColumn
            keys(0) = dt.Columns("id")
            dt.PrimaryKey = keys

            Return True
        Catch ex As Exception
            SystemError.SystemLog(ex)
            Return False
        End Try
    End Function

    Public Function initFileRootTable(ByRef dt As DataTable) As Boolean
        Try
            'テーブルにフィールドを追加
            dt.Columns.Add("actionType", Type.GetType("System.Decimal"))

            Return True
        Catch ex As Exception
            SystemError.SystemLog(ex)
            Return False
        End Try
    End Function

    Public Function ReplaceSpecialSign(ByVal str As String, ByVal strSpecialSign As String, _
                                       Optional ByVal cnt As Integer = 2) As String
        Dim retStr As String = ""
        Try
            If str.IndexOf(strSpecialSign) >= 0 Then
                Dim newValue As String = ""
                For i = 0 To cnt - 1
                    newValue &= strSpecialSign
                Next
                retStr = str.Replace(strSpecialSign, newValue)
            End If
            Return retStr
        Catch ex As Exception
            SystemError.SystemLog(ex)
            Return Nothing
        End Try
    End Function

    Private Function GetDateTimeUTtcOrLocal(ByVal intTimeType As Integer, _
                                            Optional ByVal dt As DateTime = Nothing) As DateTime
        Dim retTime As DateTime
        Try
            If dt = Nothing Then dt = DateTime.Now

            If intTimeType = 0 Then
                'UTCに変換する
                retTime = System.TimeZoneInfo.ConvertTimeToUtc(dt)
            ElseIf intTimeType = 1 Then
                'ローカル時刻に変換する
                retTime = System.TimeZoneInfo.ConvertTimeFromUtc(dt, System.TimeZoneInfo.Local)
            End If

            Return retTime
        Catch ex As Exception
            SystemError.SystemLog(ex)
            Return Nothing
        End Try
    End Function
End Class
